import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {ConfigService} from "../../../../shared/services/config.service";
import {Product2Service} from "../../../../shared/services/product2/product.service";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.scss']
})
export class ProductListComponent implements OnInit, OnDestroy {

    option: any = {
        fields: ['name', 'code'],
        keyword: '',
        catalog: 'all',
        category: 'all',
        catalogs: [],
        categories: []
    };

    products: any = [];
    _products: any = [];

    _subscriptions: Array<any> = [];

    constructor(private router: Router, public route: ActivatedRoute, private productService: Product2Service, private configService: ConfigService,
                private message: NzMessageService, private modal: NzModalService) {
    }

    ngOnInit() {
        this.option.catalogs = this.configService.config.product.catalogs;
        this.productService.getAll()
            .subscribe(res => {
                this._products = res;
                this._products.forEach(product => {
                    product.catalog = this.option.catalogs.find(item => item.code == product.catalog);
                    product.category = product.catalog.children.find(item => item.code == product.category);
                });
                this.clear();
            });
        this._subscriptions.push(this.productService.on( 'create',res => {
            const product = res;
            product.catalog = this.option.catalogs.find(item => item.code == product.catalog);
            product.category = product.catalog.children.find(item => item.code == product.category);
            this._products.push(product);
            this.filter();
        }));
        this._subscriptions.push(this.productService.on( 'delete',res => {
            const index = this._products.findIndex(item => item._id === res._id);
            index !== -1 && this._products.splice(index, 1);
            this.filter();
        }));
        this._subscriptions.push(this.productService.on( 'update',res => {
            const index = this._products.findIndex(item => item._id === res._id);
            index !== -1 && this._products.splice(index, 1, res);
            this.filter();
        }));
    }

    ngOnDestroy(): void {
        this._subscriptions.forEach( sub => {
            sub.unsubscribe();
        });
    }

    clear() {
        this.option.keyword = '';
        this.filter();
    }

    filter() {
        this.products = this._products.filter(item => {
            if (this.option.catalog != 'all' && item.catalog.code != this.option.catalog) {
                return false;
            } else {
                if (this.option.category != 'all' && item.category.code != this.option.category) {
                    return false;
                }
            }
            if (this.option.keyword.trim() === '') {
                return true;
            } else {
                return this.option.fields.some(field => {
                    if (item[field].indexOf(this.option.keyword) != -1) {
                        return true;
                    }
                    return false;
                });
            }
        });
    }


    activeType1() {
        if (this.option.catalog == 'all') {
            this.option.categories = [];
        } else {
            const catalog = this.option.catalogs.find(item => item.code == this.option.catalog);
            this.option.categories = catalog.children;
        }
        this.option.category = 'all';
        this.filter();
    }

    activeType2() {
        this.filter();
    }

    edit(item) {
        this.router.navigate(['detail',item._id], {relativeTo: this.route.parent});
    }

    delete(item) {
        this.modal.confirm({
            nzTitle: '提示！',
            nzContent: `是否确认删除？`,
            nzOkText: '确定',
            nzOkType: 'primary',
            nzOnOk: () => {
                this.productService.delete(item._id)
                    .subscribe(res => {
                        if (res.result){
                            this.message.create('success', '删除成功！');
                            this.productService.emit('delete', item);
                        } else {
                            this.message.create('warning', '删除失败！');
                        }
                    });
            }
        });
    }

    submit(event) {
        if (!event.result) return;
        if (event.mode === 0) {
            this.productService.emit('create', event.object);
        } else {
            this.productService.emit('update', event.object);
        }
    }

    sort(sort: { key: string, value: string }): void {
        if (sort.key && sort.value) {
            this._products = this._products.sort((a, b) => (sort.value === 'ascend') ? (a[sort.key].toString().localeCompare(b[sort.key].toString())) : (b[sort.key].toString().localeCompare(a[sort.key].toString())));
        }
        this.filter();
    }

}
